<script setup lang="ts">
/**
 * @file GlobalSider.vue
 * @description 全局侧边栏组件，负责根据用户角色动态生成菜单，并支持多级嵌套路由。
 */

import { computed, ref, h, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserstore'
import defaultAvatar from '@/assets/default.jpg'
import { routes } from '@/router/routers'
import checkAccess from '@/access/checkAccess'
import { DownOutlined } from '@ant-design/icons-vue'
import ACCESS_ENUM from '@/access/accessEnum'
import * as Icons from '@ant-design/icons-vue'

const userStore = useLoginUserStore()
const router = useRouter()
const route = useRoute()

// 当前选中的菜单项的 key 数组
const current = ref<string[]>([])
// 当前展开的 SubMenu 菜单项的 key 数组
const openKeys = ref<string[]>([])

/**
 * 根据用户角色动态生成可访问的菜单项。
 * @returns {Array} 过滤后的路由配置数组，用于渲染菜单。
 */
const items = computed(() => {
  const userRole = userStore.loginUser?.userRole

  // 定义不同角色的菜单白名单
  const userMenuItems = [
    '/',
    '/interview',
    '/special-exercise',
    '/community',
    '/generate-resume',
    '/my-interview-analysis',
    '/my-messages',
  ]
  const adminMenuItems = [
    '/admin/manager',
    '/admin/dashboard',
    '/admin/pending/recruiters',
    '/admin/content/Upload',
  ]
  const recruiterMenuItems = [
    '/recruiter/dashboard',
    '/recruiter/record',
    '/recruiter/appointments',
  ]
  const unLoginMenuItems = ['/', '/community']

  // 根据当前用户角色，过滤出允许访问的路由
  return routes.filter((item) => {
    // 过滤掉需要在菜单中隐藏的路由
    if (item.meta?.hideInMenu) {
      return false
    }

    // 根据角色返回对应的菜单列表
    if (userRole === ACCESS_ENUM.ADMIN) {
      return adminMenuItems.includes(item.path)
    } else if (userRole === ACCESS_ENUM.RECRUITER) {
      return recruiterMenuItems.includes(item.path)
    } else if (userRole === ACCESS_ENUM.USER) {
      return userMenuItems.includes(item.path)
    } else {
      // 未登录用户
      return unLoginMenuItems.includes(item.path)
    }
  })
})

/**
 * 将图标名称字符串转换为 Ant Design Vue 的图标组件。
 * @param {string} name - 图标的名称 (e.g., 'HomeOutlined').
 * @returns {Component | null} 对应的图标组件，如果未找到则返回 null。
 */
const getIcons = (name: string) => Icons[name] || null

/**
 * 路由切换后的全局后置钩子。
 * 用于更新当前选中的菜单项和需要展开的子菜单。
 */
router.afterEach((to) => {
  const currentPath = to.path
  current.value = [currentPath]
  const newOpenKeys: string[] = []
  // 遍历路由表，找到当前路径所在的父级和祖父级菜单，并将其 path 加入 openKeys
  for (const l1 of routes) {
    if (l1.children) {
      for (const l2 of l1.children) {
        if (l2.children) {
          if (l2.children.some((l3) => l3.path === currentPath)) {
            newOpenKeys.push(l1.path) // 展开一级菜单
            newOpenKeys.push(l2.path) // 展开二级菜单
          }
        } else if (l2.path === currentPath) {
          newOpenKeys.push(l1.path) // 展开一级菜单
        }
      }
    }
  }
  openKeys.value = newOpenKeys
})

/**
 * 点击菜单项时的回调函数。
 * @param { { key: string } } param - 包含被点击菜单项 key 的对象。
 */
const onMenuItem = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

/**
 * 组件挂载时的生命周期钩子。
 * 用于初始化时设置当前选中的菜单项和需要展开的子菜单。
 */
onMounted(() => {
  const currentPath = route.path
  current.value = [currentPath]
  const newOpenKeys: string[] = []
  // 逻辑同 router.afterEach，确保页面刷新时能正确展开菜单
  for (const l1 of routes) {
    if (l1.children) {
      for (const l2 of l1.children) {
        if (l2.children) {
          if (l2.children.some((l3) => l3.path === currentPath)) {
            newOpenKeys.push(l1.path)
            newOpenKeys.push(l2.path)
          }
        } else if (l2.path === currentPath) {
          newOpenKeys.push(l1.path)
        }
      }
    }
  }
  openKeys.value = newOpenKeys
})
</script>

<template>
  <div id="globalHeader">
    <!-- Logo 区域 -->
    <div class="logo">
      <img src="@/assets/logo.png" alt="logo" />
      <span>面试通</span>
    </div>

    <!-- 菜单容器 -->
    <div class="menu-container">
      <a-menu
        v-model:selectedKeys="current"
        v-model:openKeys="openKeys"
        mode="inline"
        @click="onMenuItem"
      >
        <!-- 遍历过滤后的顶级菜单项 -->
        <template v-for="item in items" :key="item.path">
          <!-- 如果有子菜单，则渲染为可展开的 SubMenu -->
          <a-sub-menu
            v-if="item.children && item.children.length > 0"
            :key="item.path"
            :icon="h(getIcons(item.icon))"
          >
            <template #title>{{ item.name }}</template>
            <!-- 遍历二级菜单项 -->
            <template v-for="child in item.children" :key="child.path">
              <!-- 如果二级菜单项还有子菜单 (三级菜单) -->
              <a-sub-menu
                v-if="child.children && child.children.length > 0"
                :key="child.path"
                :icon="h(getIcons(child.icon))"
              >
                <template #title>{{ child.name }}</template>
                <!-- 遍历三级菜单项 -->
                <a-menu-item
                  v-for="grandChild in child.children"
                  :key="grandChild.path"
                  :icon="h(getIcons(grandChild.icon))"
                >
                  {{ grandChild.name }}
                </a-menu-item>
              </a-sub-menu>
              <!-- 如果二级菜单项是普通菜单项 -->
              <a-menu-item v-else :key="child.path" :icon="h(getIcons(child.icon))">
                {{ child.name }}
              </a-menu-item>
            </template>
          </a-sub-menu>
          <!-- 如果没有子菜单，则渲染为普通的 MenuItem -->
          <a-menu-item v-else :key="item.path" :icon="h(getIcons(item.icon))">
            {{ item.name }}
          </a-menu-item>
        </template>
      </a-menu>
    </div>

    <!-- 用户信息区域 -->
    <div class="userInfo" v-if="userStore.loginUser?.id">
      <div class="avatar">
        <a-image
          :src="userStore.loginUser?.userAvatar ?? defaultAvatar"
          width="30px"
          alt="avatar"
        />
      </div>
      <div class="userName">
        <!-- 用户名和下拉菜单 -->
        <a-dropdown>
          <a class="ant-dropdown-link" @click.prevent>
            {{ userStore?.loginUser?.userName ?? '用户' }}
            <DownOutlined />
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item>
                <a @click="router.push('/user/userInfo')">个人中心</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="userStore.logout">退出登录</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>
    <!-- 登录/注册按钮区域 (未登录时显示) -->
    <div v-else class="userInfo">
      <a-dropdown>
        <a-button type="primary">
          登录
          <DownOutlined />
        </a-button>
        <template #overlay>
          <a-menu>
            <a-menu-item key="user">
              <a @click="router.push('/user/login')">用户登录</a>
            </a-menu-item>
            <a-menu-item key="recruiter">
              <a @click="router.push('/recruiter/login')">招聘者登录</a>
            </a-menu-item>
            <a-menu-item key="admin">
              <a @click="router.push('/admin/login')">管理员登录</a>
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </div>
  </div>
</template>

<style scoped>
#globalHeader {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 100vh;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(250, 250, 250, 0.9));
  border-radius: 12px;
  box-shadow: inset 0 0 20px rgba(24, 144, 255, 0.05);
  position: relative;
  overflow: hidden;
}

#globalHeader::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 120px;
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.15), rgba(65, 117, 232, 0.15));
  z-index: 0;
  border-radius: 12px 12px 50% 50% / 12px 12px 20% 20%;
}

.logo {
  display: flex;
  align-items: center;
  padding: 20px 16px;
  margin-bottom: 16px;
  flex-shrink: 0;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.logo:hover {
  transform: translateY(-2px);
}

.logo img {
  height: 42px;
  margin-right: 12px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
  transition: all 0.3s ease;
}

.logo:hover img {
  transform: scale(1.05);
}

.logo span {
  font-size: 20px;
  font-weight: bold;
  background: linear-gradient(135deg, rgba(24, 144, 255, 1), rgba(65, 117, 232, 1));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  letter-spacing: 1px;
}

.menu-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 12px;
  position: relative;
  z-index: 1;
  /* 滚动条样式优化 */
  scrollbar-width: thin;
  scrollbar-color: rgba(24, 144, 255, 0.3) transparent;
}

.menu-container::-webkit-scrollbar {
  width: 4px;
}

.menu-container::-webkit-scrollbar-track {
  background: transparent;
}

.menu-container::-webkit-scrollbar-thumb {
  background-color: rgba(24, 144, 255, 0.3);
  border-radius: 4px;
}

/* 覆盖Ant Design菜单样式 */
:deep(.ant-menu) {
  border-right: none;
  background: transparent;
}

:deep(.ant-menu-item) {
  margin: 8px 0;
  border-radius: 10px;
  height: 48px;
  line-height: 48px;
  font-size: 15px;
  transition: all 0.3s ease;
  color: #333;
  position: relative;
  overflow: hidden;
}

:deep(.ant-menu-item:hover) {
  color: rgb(24, 144, 255);
  background: rgba(24, 144, 255, 0.05);
}

:deep(.ant-menu-item-selected) {
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.1), rgba(65, 117, 232, 0.1)) !important;
  color: rgb(24, 144, 255) !important;
  font-weight: 500;
}

:deep(.ant-menu-item-selected::after) {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 4px;
  border-radius: 0 4px 4px 0;
  background: linear-gradient(to bottom, rgb(24, 144, 255), rgb(65, 117, 232));
}

:deep(.ant-menu-item .anticon) {
  font-size: 18px;
  margin-right: 10px;
  vertical-align: -0.15em;
}

/* 子菜单样式 */
:deep(.ant-menu-submenu) {
  border-radius: 10px;
  transition: all 0.3s ease;
}

:deep(.ant-menu-submenu-title) {
  height: 48px;
  line-height: 48px;
  font-size: 15px;
  border-radius: 10px;
  transition: all 0.3s ease;
}

:deep(.ant-menu-submenu-title:hover) {
  color: rgb(24, 144, 255);
  background: rgba(24, 144, 255, 0.05);
}

:deep(.ant-menu-submenu-selected .ant-menu-submenu-title) {
  color: rgb(24, 144, 255);
  font-weight: 500;
}

:deep(.ant-menu-submenu-arrow) {
  color: inherit;
}

.userInfo {
  display: flex;
  align-items: center;
  padding: 20px 16px;
  margin-top: auto;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(5px);
  position: relative;
  z-index: 1;
  flex-shrink: 0;
}

.userInfo .avatar {
  margin-right: 12px;
}

.userInfo .userName {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.userInfo .user-role {
  font-size: 12px;
  color: #999;
}

.userInfo .ant-btn {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  font-size: 15px;
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.9), rgba(65, 117, 232, 0.9));
  border: none;
  box-shadow: 0 2px 8px rgba(65, 117, 232, 0.2);
  transition: all 0.3s ease;
}

.userInfo .ant-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(65, 117, 232, 0.3);
  background: linear-gradient(135deg, rgb(24, 144, 255), rgb(65, 117, 232));
}

.ant-dropdown-link {
  color: #333;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
}

.ant-dropdown-link:hover {
  color: rgb(24, 144, 255);
}

:deep(.ant-dropdown-menu) {
  border-radius: 10px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

:deep(.ant-dropdown-menu-item) {
  padding: 8px 16px;
  transition: all 0.3s ease;
}

:deep(.ant-dropdown-menu-item:hover) {
  background: rgba(24, 144, 255, 0.05);
}

:deep(.ant-dropdown-menu-item a) {
  color: #333;
  transition: all 0.3s ease;
}

:deep(.ant-dropdown-menu-item:hover a) {
  color: rgb(24, 144, 255);
}
</style>
